package com.cysyz.mylib.mailsender;

import com.cysyz.mylib.mailsender.exception.MailSendException;

import java.io.UnsupportedEncodingException;
import java.util.HashSet;
import java.util.Set;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Transport;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

public class Mail {
		private Message msg;
		private Set<String> attachFilePaths = new HashSet<String>();
		private String htmlConent;
		public Mail(Message msg, String htmlConent) {
			this.msg = msg;
			this.htmlConent = htmlConent;
		}
		public void addAttacthFile(String fileFullPath) {
			attachFilePaths.add(fileFullPath);
		}
		
		public void send() {
			try {
				populateMail();
				Transport.send(msg);
			} catch (MessagingException e) {
				throw new MailSendException(e);
			}
		}
		private void populateMail() {
			try {
				if (attachFilePaths != null) {
                    MimeMultipart multipart = new MimeMultipart("mixed");
                    msg.setContent(multipart);
                    MimeBodyPart content = new MimeBodyPart();
                    content.setContent(htmlConent, "text/html;charset=UTF-8");
                    multipart.addBodyPart(content);
                    for (String attachFilePath : attachFilePaths) {
                        MimeBodyPart attachFile = new MimeBodyPart();
                        FileDataSource ds = new FileDataSource(attachFilePath);
                        attachFile.setDataHandler(new DataHandler(ds));
                        attachFile.setFileName(MimeUtility.encodeText(ds.getName(), "UTF-8", "B"));
                        multipart.addBodyPart(attachFile);
                    }

                } else {
                    msg.setContent(htmlConent, "text/html;charset=UTF-8");
                }
			} catch (MessagingException | UnsupportedEncodingException e) {
				throw new MailSendException(e);
			}
		}
	}